<?php

namespace app\cms\model;

use think\admin\Model;

class CmsStockGoods extends Model
{
  // 关联库存流水
  public function logs()
  {
    return $this->hasMany(CmsStockLog::class, 'goods_id');
  }

  // 入库操作
  public function addStock($num, $operator = null, $note = '')
  {
    $this->startTrans();
    try {
      // 更新总库存
      $this->inc('total', $num)->update();

      // 记录入库日志
      $this->logs()->save([
        'type'      => 1,
        'num'       => $num,
        'operator'  => $operator,
        'note'      => $note
      ]);

      $this->commit();
      return true;
    } catch (\Throwable $e) {
      $this->rollback();
      return $this->error($e->getMessage());
    }
  }

  // 出库操作
  public function useStock($num, $operator = null, $note = '')
  {
    $this->startTrans();
    try {
      // 使用行级锁
      $goods = self::mk()->lock(true)->find($this->id);

      // 计算可用库存
      $available = $goods->total - $goods->used;
      if ($available < $num) {
        throw new \Exception("库存不足，剩余可用库存：{$available}");
      }

      // 更新已用库存
      $goods->inc('used', $num)->update();

      // 记录出库日志
      $goods->logs()->save([
        'type'      => 0,
        'num'       => $num,
        'operator'  => $operator,
        'note'      => $note
      ]);

      // 检查库存预警
      $remaining = $goods->total - ($goods->used + $num);
      $warning = '';
      if ($remaining <= $goods->threshold) {
        // 触发预警通知
        event('StockWarning', [
          'goods'     => $goods,
          'remaining' => $remaining
        ]);
      }

      $this->commit();
      return ['status' => true, 'warning' => $warning ?? ''];
    } catch (\Throwable $e) {
      $this->rollback();
      return ['status' => false, 'error' => $e->getMessage()];
    }
  }

  // 格式化剩余库存
  public function getRemainingAttr()
  {
    return $this->total - $this->used;
  }
}
